const express = require("express");
const { default: axios } = require("axios");
const app = express();
const schedule = require("node-schedule");
const { Ilog, dateFormat } = require("./utils.js");
const port = 3008;
const { userArr, userArr2 } = require("./userArr.js"); // 用户数组

let Token = "";

// 登录获取token
const getToken = async () => {
    try {
        let url = `http://e.yvtc.edu.cn:12800/WCF/JCSJ/User/Login?para={"LOGIN_NAME":"201963280215","LOGIN_PWD":"13043X"}&_=1639791281840`;
        const { data } = await axios({
            method: "GET",
            url
        });
        const res = JSON.parse(data.d);
        if (res.Success && res.Code == "0") {
            Token = res.Data.token;
            Ilog("--token获取成功：" + res.Data.token);
        } else {
            Ilog("----token获取失败！");
            Ilog(res.Msg);
        }
    } catch (error) {
        Ilog("----token获取失败！");
        console.log(error);
    }
};

// 查询信息验证Token
const verificationToken = async () => {
    try {
        let url = `http://e.yvtc.edu.cn:12805/WCF/DGSX/GROUP_STUDENT/GetItem?para={"XH":"201900000607"}&token=${Token}`;
        const { data } = await axios({
            method: "GET",
            url
        });
        const res = JSON.parse(data.d);
        if (res.Success && res.Code == "0") {
            // 有效token不处理
            return false;
        } else {
            Ilog(res.Msg);
            Ilog("----Token失效重新获取！");
            return true;
        }
    } catch (error) {
        Ilog("----验证Token失败！");
        console.log(error);
    }
};

// 定时任务
const scheduleCronstyle = () => {
    //每分钟的第1秒定时执行一次:
    // schedule.scheduleJob("1 * * * * *", async () => {
    //     if (Token === "") {
    //         await getToken();
    //     }
    //     // token 不为空则验证token
    //     if (Token !== "") {
    //         const verifToken = await verificationToken();
    //         if (verifToken) {
    //             await getToken();
    //         }
    //     }
    //     TetsUser.forEach((i) => {
    //         signin(i.userCode, i.lat, i.lng, i.signinAddr, i.userName);
    //         journal(i.userCode, i.title, i.value, i.userName);
    //     });
    // });

    // 每天 早上6点第一波签到加写日志
    schedule.scheduleJob("0 1 6 * * *", async () => {
        if (Token === "") {
            await getToken();
        }
        // token 不为空则验证token
        if (Token !== "") {
            const verifToken = await verificationToken();
            if (verifToken) {
                await getToken();
            }
        }
        userArr.forEach((i) => {
            signin(i.userCode, i.lat, i.lng, i.signinAddr, i.userName);
            journal(i.userCode, i.title, i.value, i.userName);
        });
    });
    // 每天 早上6点第二波用户签到加写日志
    schedule.scheduleJob("0 10 6 * * *", async () => {
        if (Token === "") {
            await getToken();
        }
        // token 不为空则验证token
        if (Token !== "") {
            const verifToken = await verificationToken();
            if (verifToken) {
                await getToken();
            }
        }
        userArr2.forEach((i) => {
            signin(i.userCode, i.lat, i.lng, i.signinAddr, i.userName);
            journal(i.userCode, i.title, i.value, i.userName);
        });
    });
};

// 开启定时任务
scheduleCronstyle();

// 签到
// 用户id 经纬度 地址 用户名
const signin = async (userCode, lat, lng, signinAddr, userName) => {
    signinAddr = encodeURI(signinAddr);
    try {
        let url = `http://e.yvtc.edu.cn:12805/WCF/DGSX/SIGNIN/AddItem?para={"BATCH_ID":31,"USER_CODE":"${userCode}","LOCATION_JSON":"{\\"lat\\":${lat},\\"lng\\":${lng}}","SIGNIN_ADDR":"${signinAddr}"}&token=${Token}`;
        const { data } = await axios({
            method: "GET",
            url
        });
        const res = JSON.parse(data.d);
        if (res.Success && res.Code == "0") {
            Ilog(userName + "--签到成功！");
        } else {
            Ilog("----签到失败！" + userName);
            Ilog(res.Msg);
        }
    } catch (error) {
        Ilog("----签到失败！" + userName);
        console.log(error);
    }
};

// 日志
// 用户id 标题 内容 用户名
const journal = async (userCode, title, value, userName) => {
    let data;
    try {
        let res = await axios({
            method: "GET",
            url: "https://v1.hitokoto.cn/?c=i&min_length=6"
        });
        data = res.data;
    } catch (error) {
        // 第二次请求
        let res = await axios({
            method: "GET",
            url: "https://v1.hitokoto.cn/?c=i&min_length=6"
        });
        data = res.data;
    }
    title = encodeURI(dateFormat("YYYY-mm-dd", new Date())) || encodeURI(title);
    // 判断一言是否成功
    if (data && data.hitokoto) {
        value = encodeURI(data.hitokoto);
    } else {
        value = encodeURI(value);
    }

    try {
        let url = `http://e.yvtc.edu.cn:12805/WCF/DGSX/LOG/AddItem?para={"BATCH_ID":31,"RECORDER_TYPE":0,"USER_CODE":"${userCode}","LOG_TITLE":"${title}","LOG_CONTENT":"${value}"}&token=${Token}`;
        const { data } = await axios({
            method: "GET",
            url
        });
        const res = JSON.parse(data.d);
        if (res.Success && res.Code == "0") {
            Ilog(userName + "--日志写入成功！");
        } else {
            Ilog("----日志写入失败！" + userName);
            Ilog(res.Msg);
        }
    } catch (error) {
        Ilog("----日志写入失败！" + userName);
        console.log(error);
    }
};

app.listen(port, () => {
    console.log("服务开启成功！端口为：" + port);
    console.log("当前签到人数：" + (userArr.length + userArr2.length) + " 人");
});
